package com.ssyc.student.activity;

import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyListView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.common.view.flowlayout.FlowLayout;
import com.ssyc.common.view.flowlayout.TagAdapter;
import com.ssyc.common.view.flowlayout.TagFlowLayout;
import com.ssyc.student.R;
import com.ssyc.student.adapter.StWriteAnswerLvAdapter;
import com.ssyc.student.bean.CommitInfo;
import com.ssyc.student.bean.ResultInfo;
import com.ssyc.student.bean.WriteInfo;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--写作第二题型界面
 * Created by Administrator on 2018/5/25 0025.
 */

public class StudentWriteTwoActivity extends BaseActivity implements View.OnClickListener {

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //更新的标识和重做的标识
    public static final int UPDATETYPE = 100;
    public static final int REFORMTYPE = 101;

    //加载框布局
    private RelativeLayout rlLoading;

    //返回
    private ImageView ivBack;

    //文章的标题
    private TextView tv__article_title;

    //文章的内容
    private TextView tv_article_content;

    //模拟的题目
    private String topic;

    //定义的下划线的替换符号,15个空
    public static String regStr = "_______________";

    //用于保存替换下划线为选择答案的map
    public Map<Integer, String> underLineMap;

    //使用填空二字切割服务器返回的题目内容获取的字符串数组
    private String[] contents;

    //答案
    private String[] Answers;

    //序号
    private String[] Nums = {"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩"};

    //变红色的位置数
    private static final int count = 16;

    //流式布局
    public TagFlowLayout mFlowLayout;

    //json
    private String dataJson;

    //流式布局适配器
    private TagAdapter adapter;

    //提供题目选项的数据集合
    private List<String> answerInfos;

    //已选答案的集合
    private Map<Integer, Integer> choiceList;

    //展示答案列表
    private MyListView lvAnswer;

    //答案列表适配器
    private StWriteAnswerLvAdapter answerAdapter;

    //提供答案的数据集合
    private List<String> datas;

    //确定按钮
    private ImageView iv_sure;


    //用于保存做题的选择题目答案的Map,key为当前的位置,value为选择的答案
    public static Map<Integer, String> chooseAnswerMap;

    //用于保存用户答题的对错的Map,key为当前的位置,value为答题的状态值
    public static Map<Integer, Boolean> answerMap;

    //LessonId
    private String lessonId;

    //GradeId
    private String gradeId;

    private WriteInfo.DataBean.QuestionListBean info;

    //时间rowid
    private String rowId;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_write_two;
    }

    @Override
    protected void init() {

        //初始化视图
        initView();

        //获取传递的数据
        initIntent();

        showContent();
    }

    //静态代码块
    {
        //初始化存放填空位置的内容的map
        underLineMap = new LinkedHashMap<>();
        choiceList = new LinkedHashMap<>();
    }

    /**
     * 初始化视图
     */
    public void initView() {
        mFlowLayout = findViewById(R.id.id_flowlayout);
        rlLoading = findViewById(R.id.rl_loading_view);
        rlLoading.setVisibility(View.VISIBLE);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tv__article_title = findViewById(R.id.tv__article_title);
        tv_article_content = findViewById(R.id.tv_article_content);

        lvAnswer = findView(R.id.lv_answer);
        iv_sure = findView(R.id.iv_sure);
        iv_sure.setOnClickListener(this);

        if (null != rlLoading) {
            rlLoading.setVisibility(View.GONE);
        }
    }


    /**
     * 获取传递的数据
     */
    private void initIntent() {

        StudentWriteActivity.getChooseAnswerMap().get(0);

        //已选答案集合
        answerInfos = new ArrayList<>();
        datas = new ArrayList<>();
        //获取json
        dataJson = getIntent().getStringExtra("json");

        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);
        rowId = getIntent().getStringExtra("rowid");

        Log.e("test","写作json："+dataJson);

        //服务器数据
        info = GsonUtil.jsonToBean(dataJson, WriteInfo.DataBean.QuestionListBean.class);
        //设置标题
        setQuestionTitle(info);

        setContent(info);
        //获取题目选项集合
        for (int i = 0; i < info.getOptions_list().size(); i++) {
            answerInfos.add(info.getOptions_list().get(i).getOp());
        }
        //分割答案
        Answers = info.getAnswer().split("￠");

        //设置答案集合
        for (int i = 0; i < Answers.length; i++) {
            datas.add(Nums[i] + " " + Answers[i]);
        }
        //设置流式布局选项
        initLv();

        //初始化Map
        for (int i = 0; i < info.getOptions_list().size(); i++) {
            choiceList.put(i, -1);
        }

        for (int i = 0; i < answerInfos.size(); i++) {
            int length = 15 - answerInfos.get(i).length() + 1;
            for (int j = 0; j < length; j++) {
                if (j % 2 == 0) {
                    answerInfos.set(i, answerInfos.get(i) + " ");
                } else {
                    answerInfos.set(i, " " + answerInfos.get(i));
                }
            }
        }
    }

    /**
     * 亮屏进入
     */
    @Override
    protected void onResume() {
        super.onResume();

        //记录进入时间
    }

    /**
     * 息屏结束计时
     */
    @Override
    protected void onPause() {
        super.onPause();

        //上传服务器记录时间的接口
        RecordTimeUtil.httpExitTime(rowId, this);


    }


    /**
     * 设置文章标题
     */
    private void setQuestionTitle(WriteInfo.DataBean.QuestionListBean info) {
        if (!TextUtils.isEmpty(info.getBig_title())) {
            tv__article_title.setText(info.getBig_title());
        }
    }

    /**
     * 设置文章内容
     * 用下划线替代"填空"后进行回显
     *
     * @param questionListBean
     */
    private void setContent(WriteInfo.DataBean.QuestionListBean questionListBean) {
        String questionContent = questionListBean.getQuestion_content();

        if (!TextUtils.isEmpty(questionContent)) {
            //切割字符串
            contents = questionContent.split("填空");

            //初始化Map,给每个需要替换下划线的值都初始为空串
            for (int i = 0; i < contents.length - 1; i++) {
                underLineMap.put(i, "");
            }

            //将填空全部替换成下划线
            tv_article_content.setText(questionContent.replace("填空", regStr));
        }
    }


    /**
     * 设置流式布局
     */
    private void initLv() {

        final LayoutInflater mInflater = LayoutInflater.from(this);

        adapter = new TagAdapter<String>(answerInfos) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.stu_write_two_tv,
                        mFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        };

        //添加适配器
        mFlowLayout.setAdapter(adapter);

        //流式布局点击事件
        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                int ishas = -1;
                for (int i = 0; i < choiceList.size(); i++) {
                    if (choiceList.get(i) == position) {
                        ishas = i;
                    }
                }
                //判断是否存在
                if (ishas != -1) {
                    return false;
                } else {
                    choiceList.put(position, position);
                }

                setContent(position);
                return true;
            }
        });
    }

    /**
     * 设置答案
     */
    private void setContent(int position) {
        //获取选择答案的位置
        int pos = position;

        //回显需要显示的选择答案的序列号,注意这里一定是要2个空格+序号+2个空格,跟替换的5个下划线长度保持一致
        String chooseAnswerNum = answerInfos.get(pos);

        //拼接需要回显的答案,首先需要判断保存的下划线map中空串的位置
        if (contents != null && contents.length != 0) {
            for (int i = 0; i < contents.length - 1; i++) {
                if (TextUtils.isEmpty(underLineMap.get(i)) || regStr.equals(underLineMap.get(i))) {
                    //保存或者替换第一个Map没有保存的值
                    underLineMap.put(i, chooseAnswerNum);
                    break;
                }
            }

            //重新设置文本的值
            setShowContent(true);
        }

    }


    /**
     * 处理通讯事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (busInfo != null && busInfo.getType() == 4) {
            //表示收到了更新页面填空题显示的事件
            //获取选择答案的位置
            int pos = busInfo.getPos();

            //回显需要显示的选择答案的序列号,注意这里一定是要2个空格+序号+2个空格,跟替换的5个下划线长度保持一致
            String chooseAnswerNum = answerInfos.get(pos);

            //拼接需要回显的答案,首先需要判断保存的下划线map中空串的位置
            if (contents != null && contents.length != 0) {
                for (int i = 0; i < contents.length - 1; i++) {
                    if (TextUtils.isEmpty(underLineMap.get(i)) || regStr.equals(underLineMap.get(i))) {
                        //保存或者替换第一个Map没有保存的值
                        underLineMap.put(i, chooseAnswerNum);
                        break;
                    }
                }

                //重新设置文本的值
                setShowContent(true);
            }

            //这里是接受到用户选择答案后改变Map的存值后在发送重做消息给用户提交答案的Fragment界面
            BusInfo reformInfo = new BusInfo();
            reformInfo.setType(REFORMTYPE);
            EventBus.getDefault().post(reformInfo);
        } else if (StudentShowPrepareDetectionAnswerActivity.LOOKANSWER == busInfo.getType()) {
            //让展示题目的TextView不可交互
            tv_article_content.setEnabled(false);
        }
    }


    /**
     * 重新设置文本的值
     */
    private void setShowContent(boolean isflag) {

        //取值,定义需要回显的问题
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < contents.length; i++) {
            //添加分割的数组内容
            sb.append(contents[i]);
            //map的key是从0到contents.length-2
            if (i != contents.length - 1 && i != contents.length) {
                if (!TextUtils.isEmpty(underLineMap.get(i))) {
                    //当前下划线有值,添加2个空格+当前位置的值+2个空格,一共5个字符
                    sb.append(underLineMap.get(i));
                } else {
                    //当前下划线没有值,添加5个下划线
                    sb.append(regStr);
                }
            }
        }

        //获取需要回显的题目内容
        String showTopics = sb.toString();

        SpannableStringBuilder content = new SpannableStringBuilder(showTopics);

        //设置回显的题目内容的文字变红,下划线以及需要点击的文字
        if (underLineMap != null && underLineMap.size() != 0 && contents != null && contents.length != 0) {

            for (int i = 0; i < underLineMap.size(); i++) {
                //确定空格的位置
                int start = 0;
                if (i == 0) {
                    start = contents[0].length();
                } else {
                    for (int j = 0; j <= i; j++) {
                        start += contents[j].length();
                    }
                    for (int k = 0; k <= i - 1; k++) {
                        start += underLineMap.get(k).length();
                    }
                }


                if (!TextUtils.isEmpty(underLineMap.get(i))) {
                    setTextViewState(isflag, i, content, start);
                }
            }

            //设置答案
            tv_article_content.setText(content);
        }
    }


    /**
     * 设置文字变色的方法和加下划线的方法
     *
     * @param content
     * @param start
     */

    private void setTextViewState(boolean isFlag, int pos, SpannableStringBuilder content, int start) {
        ForegroundColorSpan colorSpan = null;
        if (isFlag) {
            colorSpan = new ForegroundColorSpan(Color.parseColor("#FF0000"));
        } else {
            colorSpan = new ForegroundColorSpan(Color.parseColor("#A3A3A3"));
        }

        content.setSpan(colorSpan, start, start + count, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        content.setSpan(new UnderlineSpan(),
                start, start + count, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        //设置点击事件
        content.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                //通过EventBus通知Fragment界面进行答案选项重置,这里点击当前位置后清除选择的答案的同时需要告知
                //Fragment界面的可选择答案的状态重置,变成可选择的状态
                BusInfo info = new BusInfo();
                info.setType(UPDATETYPE);
                info.setPos(pos);
                EventBus.getDefault().post(info);
                //重新点击后改变Map当前存放的值为
                underLineMap.put(pos, regStr);
                setShowContent(false);
                for (int i = 0; i < choiceList.size(); i++) {
                    choiceList.put(i, -1);
                }
            }
        }, start, start + count, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置该方法后,点击事件才能生效
        tv_article_content.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * 页面控件的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.iv_sure) {
            //确定
            for (int i = 0; i < underLineMap.size(); i++) {
                if ("".equals(underLineMap.get(i))) {
                    UIHelper.showToast(this, "请完成所有填空");
                    return;
                }
            }

            answerAdapter = new StWriteAnswerLvAdapter(getBaseContext(), datas, R.layout.student_lv_write);
            lvAnswer.setAdapter(answerAdapter);

            //提交成绩
            httpCommit();
        }
    }


    /**
     * 做完题目后上传服务器
     */
    private void httpCommit() {


        CommitInfo commitInfo = new CommitInfo();

        //级别
        commitInfo.setGrade_id(gradeId);

        //课程编号
        commitInfo.setLesson_id(lessonId);

        //模块编号
        commitInfo.setModule_id("16");

        //题目总数量
        commitInfo.setAmount(info.getDetail_list().size() + 1 + "");

        //正确题目数量
        commitInfo.setAmount_t("0");

        //总分
        commitInfo.setScore("0");

        //得分
        commitInfo.setScore_t("0");

        //获取上传时间
        long useTime = TimeCount.newInstance().getTotalTime() + (System.currentTimeMillis() - TimeCount.newInstance().getLastTime());

        //转化为秒
        String seconds = useTime / 1000 + "";

        commitInfo.setSeconds(seconds);

        List<CommitInfo.SubjectBean> subjectBeans = new ArrayList<>();

        //多个空
        for (int i = 0; i < underLineMap.size(); i++) {
        //连词成句
        CommitInfo.SubjectBean subjectBean = new CommitInfo.SubjectBean();


        //题目编号
        subjectBean.setQuestion_id(info.getQuestion_id() + "");
        //题型编号
        subjectBean.setType_id(info.getQuestion_type() + "");
        //获取该项选择的内容
        String content = "";
        content = underLineMap.get(i).trim();


        //填空内容
        subjectBean.setContent(content);

        //得分
        subjectBean.setScore("0");
        //判断正误
            if(underLineMap.get(i).trim().equals(Answers[i].trim())){
                //正确
                subjectBean.setResult("1");
            }else{
                subjectBean.setResult("0");
            }
            Log.i("test", "答案是:" + Answers[i].trim());
        subjectBeans.add(subjectBean);
        }

        commitInfo.setSubject(subjectBeans);

        //转换成JSON字符串
        String postServerJson = GsonUtil.objectToJson(commitInfo);

        Log.i("test", "上传给服务器的JSON是:" + postServerJson);

        CustomDialogManager.show(this, "上传中...");

        Map<String, String> map = new HashMap<>();
        map.put("type", "24");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("studys", postServerJson);
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");
        if (TextUtils.isEmpty(RecordTimeUtil.energy)) {
            map.put("energy", "0");
        } else {
            map.put("energy", RecordTimeUtil.energy);
        }

        HttpUtils.post(HttpAdress.COMMITSCORE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                ResultInfo info = null;
                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (info != null) {
                        if ("200".equals(info.state)) {
                            //上传成功
                            UiUtils.Toast("提交成功", false);
                            //跳转到展示阅读答题结果的界面同时需要通过将Activity的计时时间携带给下个界面
//                            goToShowAnswerActivity();
                            iv_sure.setVisibility(View.GONE);
                            tv_article_content.setEnabled(false);
                        } else {
                            UiUtils.Toast("提交失败,错误码是:" + info.state, false);
                            Log.i("test", "错误码是:" + info.state);
                        }
                    }
                }
            }
        });


    }
}
